package com.extsci.monitor;

import com.alibaba.fastjson.JSON;
import com.extsci.monitor.entity.Message;
import com.extsci.monitor.factory.RabbitmqFactory;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Base64;
import java.util.Date;

import static com.extsci.monitor.config.RabbitmqConfig.EXCHANGE_NAME;
import static com.extsci.monitor.config.RabbitmqConfig.ROUTING_KEY;

/**
 * 邮件消息监听
 * @author ccoke
 */
@Component
@Log4j
public class EmailMonitor {
    private static final Integer SIZE = 1024;
    private static final String UTF8 = "UTF-8";

    @Value("${server.port}")
    private Integer port;

    @Autowired
    private RabbitmqFactory rabbitmqFactory;

    public void start() throws IOException {
        final DatagramSocket socket=new DatagramSocket(port);
        log.info("server start: " + InetAddress.getLocalHost() + ":" + port);
        while(true){
            byte[] data=new byte[SIZE];
            // 创建数据包
            DatagramPacket packet=new DatagramPacket(data,data.length);
            // 开始监听
            socket.receive(packet);
            // 开辟线程处理消息
            Thread thread=new MyThread(packet);
            thread.start();
        }
    }

    // 判断是否以=?开头 ?=结尾
    private boolean isBase64(String str){
        return str.startsWith("=?") && str.endsWith("?=");
    }

    class MyThread extends Thread {
        private final DatagramPacket packet;

        public MyThread(DatagramPacket packet){
            this.packet = packet;
        }

        @Override
        public void run() {
            // 打印数据
            byte[] ans=new byte[packet.getLength()];
            System.arraycopy(packet.getData(), 0, ans, 0, packet.getLength());
            String info=new String(ans,0,packet.getLength());
            // 进行json解析
            Message message = JSON.parseObject(info, Message.class);
            System.out.println(message);
            log.info("recieve email: " + message);
            String subject = message.getSubject();
            if (subject != null
                    && !"".equals(subject.trim())
                    && isBase64(subject)){
                // 截取主题
                String sub = (subject.split("\\?"))[3];
                // 主题编码转换
                final Base64.Decoder decoder = Base64.getDecoder();
                try {

                    message.setSubject(new String(decoder.decode(sub), UTF8));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            // 时间格式转换
            message.setSendDate(new Date(message.getDate()));
            rabbitmqFactory.sendMessage(EXCHANGE_NAME, ROUTING_KEY, message);
        }
    }
}
